package com.java.module.chat.util.netty;

import com.google.common.base.Splitter;

import com.java.common.constant.Constants;
import com.java.common.service.ApiTokenService;
import com.java.common.utils.crypto.RsaKit;
import com.java.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.util.Map;

/**
 * ChatKit
 * 
 * @author yilabao
 * @date 2021年9月30日
 */
public class ChatKit {

    private static final Logger LOG = LoggerFactory.getLogger(ChatKit.class);

    private static final String TOKEN = "token";

    /**
     * 发送消息
     * 
     * @param toUid
     * @param msg
     */
    public static void sendMsg(Long toUid, String msg) {
        ChatHandler.sendMsg(toUid, msg);
    }

    /**
     * 用户是否在线
     *
     * @param uid uid
     * @return boolean
     */
    public static boolean isOnline(Long uid) {
        return ChatHandler.isOnline(uid);
    }

    /**
     * 获取连接用户uid
     * 
     * @param uri
     * @return Long
     */
    public static Long getUidByUri(String uri) {
        Long uid = null;
        String token = ChatKit.getParam(uri, TOKEN);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String mobile = ChatKit.getParam(uri, "mobile");
        if (StringUtils.isNotBlank(mobile)) {
            return SpringUtils.getBean(ApiTokenService.class).getLoginUserId(token);
        }
        try {
            uid = Long.parseLong(RsaKit.decrypt(URLDecoder.decode(token, Constants.UTF8)));
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return uid;
    }

    /**
     * 获取URL中的参数值
     * 
     * @param url
     * @param name
     * @return String
     */
    public static String getParam(String url, String name) {
        String questionMark = "?";
        if (StringUtils.isAnyBlank(url, name) || !url.contains(questionMark)) {
            return null;
        }
        String params = url.substring(url.indexOf(questionMark) + 1, url.length());
        Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
        return split.get(name);
    }

}
